var express = require('express');
var router = express.Router();
var sqlQuery = require('../../lcMsql')
var fs = require('fs')
let multer = require('multer')
//配置对象
let upload = multer({dest:"./public/upload"})

var userListRouter = require('../users/userListRouter')
var userListRouter2 = require('../users/userListRouter2')


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('用户管理');
});

router.get('/userinfo', async function(req, res, next) {
  let username = req.session.username
  let sqlStr = 'select * from user where username = ?'
  let result = await sqlQuery(sqlStr,[username])
  let users = result[0]
  let roles = await getRoles()
  let options = {users,roles}
  res.render('admin/users/info',options)
 

});

//加入上传的中间件
router.post('/selfimgupload',upload.single('imgfile'), async (req,res)=>{
  let result = renamePath(req)
   //改名后的结果上传数据库
   let username = req.session.username;
   let str = 'update user set imgheader = ? where username = ?'
  await sqlQuery(str,[result.imgUrl,username])

  res.json(result)
})

router.post('/info',async (req,res)=>{
  let password = req.body.password
  let email = req.body.email
  let phone = req.body.phone
  let username = req.body.username
  let roleid = req.body.roleid
  let sqlStr = 'update user set password = ?,email = ?,phone = ?, roleid = ? where username = ?';
  let arr = [password,email,phone,roleid,username]

  await sqlQuery(sqlStr,arr)
  res.json({
    state:'ok',
    content:"个人信息修改成功"
  })
})

function renamePath(req,res){
  console.log(req.file)
  //因为直接上传的文件没有命名，所以用fs重新命名下
let oldPath = req.file.destination + '/' + req.file.filename;
let Path = req.file.destination + '/' + req.file.filename + req.file.originalname;
fs.rename(oldPath,Path,()=>{
 console.log('改名成功')
})

return {
  state:'ok',
  imgUrl:"/upload/"+ req.file.filename + req.file.originalname
}
}

async function getRoles(){
  let sqlStr = 'select * from role';
  let result = await sqlQuery(sqlStr)
  return result
}

function jiami(str){
  let salt = "fjdsoigijasoigjasdiodgjasdiogjoasid"
  let obj = crypto.createHash('md5')
  str = salt+str;
  obj.update(str)
  return obj.digest('hex')
}


router.use('/userlist1',userListRouter)
router.use('/userlist2',userListRouter2)

module.exports = router;
